// 线程池
#pragma once

#include <iostream>
#include <pthread.h>
#include <vector>
#include <queue>
#include <string>
#include <unistd.h>
#include "Task.hpp"

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

static const int defalutnum = 5;

template <class T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void unLock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Wake()
    {
        pthread_cond_signal(&_cond);
    }
    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }
    std::string GetThreadName(pthread_t tid)
    {
        for (const auto &ti : _threads)
        {
            if (ti.tid == tid)
                return ti.name;
        }
        return nullptr;
    }

public:
    // 检测任务
    // 在类内，该函数的默认参数为(ThreadPool *this,void *args)
    static void *HandlerTask(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        std::string name = tp->GetThreadName(pthread_self());

        while (true)
        {
            tp->Lock();

            while (tp->IsQueueEmpty())
            {
                tp->Sleep();
            }
            T t = tp->Pop();

            tp->unLock();

            t();
        }

        return nullptr;
    }
    // 创建线程
    void Start()
    {
        int num = _threads.size();
        for (int i = 0; i < num; i++)
        {
            _threads[i].name = "thread-" + std::to_string(i + 1);
            pthread_create(&_threads[i].tid, nullptr, HandlerTask, this);
        }
    }
    void Push(const T &t)
    {
        Lock();
        _tasks.push(t);
        Wake();
        unLock();
    }
    T Pop()
    {
        T t = _tasks.front();
        _tasks.pop();

        return t;
    }
    static ThreadPool<T> *GetInstance()
    {
        if (nullptr == _tp)
        {
            pthread_mutex_lock(&_lock);
            if (nullptr == _tp)
            {
                std::cout << "log: singleton create done first!" << std::endl;
                _tp = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&_lock);
        }

        return _tp;
    }

private:
    ThreadPool(int num = defalutnum)
        : _threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
    ThreadPool(const ThreadPool<T> &) = delete;
    const ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

private:
    std::vector<ThreadInfo> _threads; // 线程管理
    std::queue<T> _tasks;             // 任务管理

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *_tp;
    static pthread_mutex_t _lock;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;